<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- 上述3个meta标签*必须*放在最前面，任何其他内容都*必须*跟随其后！ -->
    <meta name="description" content="">
    <meta name="author" content="">

    <title>wishtk</title>

    <!-- Bootstrap core CSS -->
    <link href="static/bower_components/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">
  </head>

  <body>

    <nav class="navbar">
      <div class="container-fluid">
        <div class="navbar-header">
            <?php if ($page == 'recent_tickets') { ?>
                <a class="navbar-brand switch_special_attention" href="special_attention.php">
                    wish recent ticket - (click to switch)
                </a>
            <?php } else { ?>
                <a class="navbar-brand switch_special_attention" href="index.php">
                    special attention ticket - (click to switch)
                </a>
            <?php } ?>
        </div>
      </div>
    </nav>

    <div class="container-fluid">
        <div class="row">
            <div class="col-md-4">
            <?php if ($page == 'special_attention_tickets') { ?>
                <div class="input-group pull-left">
                    <input type="text" class="form-control" placeholder="Ticket Id..." id="special_attention_input">
                    <span class="input-group-btn">
                        <button class="btn btn-default" type="button" id="add_special_attention">Add</button>
                    </span>
                </div>
            <?php } ?>
            </div>
            <div class="col-md-8">
                <p class="pull-right label label-primary" style="line-height: 25px; font-size: 16px">
                    最后更新时间：<?php echo date('Y-m-d H:i:s', $lastUpdate); ?>
                </p>
            </div>
        </div>
        <div class="row">
            <div class="col-md-12">
                <table class="table table-bordered">
                    <tr>
                        <th class="text-center" width="96">Number</th>
                        <th class="text-center" width="96">Open Date</th>
                        <th class="text-center" width="96">Item</th>
                        <th class="text-center" width="30">Total</th>
                        <th class="text-center" width="96">Tracking</th>
                        <th class="text-center" width="56">Ago</th>
                        <th class="text-center">Last Message</th>
                        <th class="text-center" width="250">Operation</th>
                    </tr>
                <?php 
                    $i = 0;
                    foreach ($tickets as $ticketId => $ticket) {
                        $lastReply = end($ticket['replies']);
                        $lastReplyMessage = $lastReply['message'];
                ?>
                    <tr>
                        <td class="text-center <?php echo $lastReply['sender_id'] == 3 ? 'danger' : ($lastReply['sender_id'] == 0 ? 'warning' : ''); ?>">
                            <?php echo ++$i; ?>
                        </td>
                        <td>
                            <a href="http://merchant.wish.com/ticket/<?php echo $ticketId; ?>" target="_blank">
                                <?php echo $ticket['open_date']; ?>
                            </a>
                        </td>
                        <td style="word-break: break-all;">
                            <?php
                                foreach ($ticket['items'] as $ticketItem) {
                                    echo $ticketItem['sku']."x".$ticketItem['quantity']."<mark>($".$ticketItem['total'].")</mark>";
                                    echo "<br />";
                                }
                            ?>
                        </td>
                        <td>
                            <?php
                                $total = 0;
                                foreach ($ticket['items'] as $ticketItem) {
                                    $total += $ticketItem['total'];
                                }
                                if ($total > 5) {
                                    $css = 'label-danger';
                                } elseif ($total > 3) {
                                    $css = 'label-warning';
                                } else {
                                    $css = 'label-info';
                                }
                                echo "<span class='label {$css}'>\${$total}</span>";
                            ?>
                        </td>
                        <td>
                            <?php
                                foreach ($ticket['items'] as $ticketItem) {
                                    echo '<a target="_blank" href="'.$ticketItem['shipping_details']['tracking_url'].'">'.$ticketItem['shipping_details']['tracking_id'].'</a>';
                                    echo "<br />";
                                }
                            ?>
                        </td>
                        <td>
                            <?php
                                foreach ($ticket['items'] as $ticketItem) {
                                    echo $ticketItem['shipped_days_ago']."天";
                                    echo "<br />";
                                }
                            ?>
                        </td>
                        <td>
                            <a target="_blank" href="http://translate.google.cn/#auto/en/<?php echo $lastReplyMessage; ?>">Google翻译</a>
                            |
                            <a target="_blank" href="javascript:void(0)" class="viewTicketContext" data-ticketId="<?php echo $ticketId;?>">查看上下文</a>
                            <br />
                            <?php echo str_replace("\n", '<br />', $lastReplyMessage); ?>
                        </td>
                        <td>
                            <a href="javascript:void(0)" class="btn btn-primary selectTicketTplBtn" data-ticketId="<?php echo $ticketId;?>">回复</a>
                        </td>
                    </tr>
                <?php } ?>
                </table>
            </div>
        </div>
    </div>

    <!-- Modal -->
    <div class="modal fade" id="ticketTplModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
      <div class="modal-dialog" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            <h4 class="modal-title" id="myModalLabel">选择模板</h4>
          </div>
          <div class="modal-body">
            <div class="radio">
              <label>
                <input class="useTicketTpl" type="radio" name="ticketTpl" value="sorry that you have problem with the cable. We want to make sure that whether your car has the AUX decoding function and can read the U disk or not. If your car has the AUX plug but could not read the U disk, the cable won't work. Hope you could check the instruction of your car again. And second we want to remind you that for most cars you could not establish folders in your mp3 or U disk and only mp3 format songs can be played. Hope our suggestion will help you. If you have any other problems, please feel free to contact us. " checked>
                <span class="ticketTplContent">
                <strong>Item Does Not Work as Described</strong><br />
                sorry that you have problem with the cable. We want to make sure...
                </span>
              </label>
            </div>
            <div class="radio">
              <label>
                <input class="useTicketTpl" type="radio" name="ticketTpl" value="sorry that the shipping is late. We have checked for you, the package has arrived in your country. We suggest you contact your local post office and ask the status of your package. If you still haven't received it in 5 days, please tell us. We would like to resend the item for you. Is it OK for you? Hope you will receive it soon.">
                <span class="ticketTplContent">
                <strong>Late or Missing</strong><br />
                sorry that the shipping is late. We have checked for you, the package...
                </span>
              </label>
            </div>
            <textarea placeholder="输入要回复的内容..." class="form-control" id="ticketTplInput" rows="10"></textarea>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            <button type="button" class="btn btn-primary" id="replyBtn">Reply</button>
          </div>
        </div>
      </div>
    </div>

    <!-- Modal -->
    <div class="modal fade" id="ticketContextModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
      <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            <h4 class="modal-title" id="myModalLabel">Ticket Context</h4>
          </div>
          <div class="modal-body">
            <table class="table" id="ticketContextTable">
            </table>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
          </div>
        </div>
      </div>
    </div>

    <!-- Bootstrap core JavaScript
    ================================================== -->
    <!-- Placed at the end of the document so the pages load faster -->
    <script src="../static/bower_components/jquery/dist/jquery.min.js"></script>
    <script src="../static/bower_components/bootstrap/dist/js/bootstrap.min.js"></script>
    <script src="../static/bower_components/bootstrap/js/modal.js"></script>
    <script>
        $('#add_special_attention').click(function(){
            var ticket_id = $.trim($('#special_attention_input').val());
            if (!ticket_id) {
                alert('ticket_id is required');
                return false;
            }
            $.ajax({
                url: 'input.php',
                method: 'GET',
                data: {'ticket_id': ticket_id},
                before: function() {
                    $('#add_special_attention').text('Adding...').attr('disabled', 'disabled');
                },
                success: function(resp) {
                    if (resp == 'success') {
                        window.location.href = 'special_attention.php';
                    } else {
                        alert(resp);
                    }
                },
                error: function() {
                    alert('添加失败请重试');
                },
                complete: function() {
                    $('#add_special_attention').text('Add').removeAttr('disabled');
                }
            })
        });

        var ticketTplWrapper = function(ticketTpl) {
            return "Dear Customer,\n\n"+ticketTpl+"\n\nWish you a good day.";
        };
        $('.selectTicketTplBtn').click(function(){
            $('#ticketTplModal').modal('show');
            $('#replyBtn').attr('data-ticketId', $(this).attr('data-ticketId'));
        });
        $('#ticketTplInput').val(ticketTplWrapper($('input[name="ticketTpl"]:checked').val()));
        $('.useTicketTpl').click(function(){
            var ticketTpl = ticketTplWrapper($(this).val());
            $('#ticketTplInput').val(ticketTpl);
        });
        $('#replyBtn').click(function(){
            var replyTicketId = $(this).attr('data-ticketId');
            var reply = $.trim($('#ticketTplInput').val());
            if (reply == '') {
                alert('回复内容不能为空哦。');
                return false;
            }
            var replyBtn = $(this);
            if (replyBtn.attr('data-pending') == 1) {
                alert('处理中，请稍后...');
                return false;
            }
            $.ajax({
                url: "index.php?a=reply_ticket",
                method: "POST",
                data: "ticket_id="+replyTicketId+"&reply="+reply,
                dataType: "json",
                beforeSend: function() {
                    replyBtn.text('处理中...');
                    replyBtn.attr('data-pending', 1);
                },
                success: function(resp) {
                    if (resp.status == 1) {
                        if (confirm('回复成功，是否跳转至wish查看？')) {
                             window.open("http://merchant.wish.com/ticket/"+replyTicketId);
                        } else {
                            $('#ticketTplModal').modal('hide');
                            window.location.reload();
                        }
                    } else {
                        alert(resp.msg);
                    }
                    replyBtn.text('回复');
                    replyBtn.removeAttr('data-pending');
                },
                error: function(resp) {
                    alert('操作失败，请重试。');
                    replyBtn.text('回复');
                    replyBtn.removeAttr('data-pending');
                }
            })
        });

        $('.viewTicketContext').click(function(){
            var ticketId = $(this).attr('data-ticketId');
            var viewBtn = $(this);
            if (viewBtn.attr('data-pending') == 1) {
                alert('查询中，请稍后...');
                return false;
            }
            $.ajax({
                url: "index.php?a=view_ticket",
                method: "POST",
                data: "ticket_id="+ticketId,
                dataType: "json",
                beforeSend: function() {
                    viewBtn.text('查询中...');
                    viewBtn.attr('data-pending', 1);
                },
                success: function(resp) {
                    if (resp.status == 1) {
                        var rows = '';
                        rows += '<tr>';
                        rows += '<th>Sender</th>';
                        rows += '<th class="text-center">Message</th>';
                        rows += '<th>Translated</th>';
                        rows += '</tr>';
                        for (key in resp.data) {
                            ticket_sender = resp.data[key].Reply.sender;
                            ticket_message = resp.data[key].Reply.message;
                            if (ticket_sender == 'user') {
                                translated_message = resp.data[key].Reply.translated_message;
                                rowStyle = 'info';
                            } else {
                                translated_message = '';
                                rowStyle = 'active';
                            }
                            rows += "<tr class='"+rowStyle+"'>";
                            rows += "<td>"+ticket_sender+"</td>";
                            rows += "<td>"+ticket_message.replace(/\n/g, "<br/>")+'<br /><a target="_blank" href="http://translate.google.cn/#auto/en/'+ticket_message+'">Google翻译</a>'+"</td>";
                            rows += "<td>"+translated_message+"</td>";
                            rows += "</tr>";
                        }
                        $('#ticketContextTable').html(rows);
                        $('#ticketContextModal').modal('show');
                    } else {
                        alert(resp.msg);
                    }
                    viewBtn.text('查看上下文');
                    viewBtn.removeAttr('data-pending');
                },
                error: function(resp) {
                    alert('操作失败，请重试。');
                    viewBtn.text('查看上下文');
                    viewBtn.removeAttr('data-pending');
                }
            });
        });
    </script>
  </body>
</html>
